package com.yy.wga.wechat.feign.api.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yy.wga.common.core.dto.BaseReqDTO;
import com.yy.wga.common.util.common.StringUtils;
import com.yy.wga.common.util.sign.SignUtils;
import com.yy.wga.common.web.intereceptor.RequestHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * feign拦截器
 *
 * @author guochao
 * @des 描述内容
 * @date 2023-08-30
 */
public class WechatFeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        JSONObject params = new JSONObject();
        // 获取请求体
        String body = template.body() != null ? new String(template.body(), StandardCharsets.UTF_8) : "";
        if (StringUtils.isNotBlank(body)) {
            JSONObject bodyObject = JSON.parseObject(body);
            params.putAll(bodyObject);
        }

        // 获取URI参数
        String url = template.url();
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
        Map<String, String> queryMap = builder.build().getQueryParams().toSingleValueMap();
        if (!CollectionUtils.isEmpty(queryMap)) {
            params.putAll(queryMap);
        }
        JSONObject headerObject = new JSONObject();
        BaseReqDTO baseRequest = RequestHolder.getBaseRequest();
        if (baseRequest != null) {
            baseRequest.setTimeStamp(System.currentTimeMillis());
            String baseRequestJson = JSON.toJSONString(baseRequest);
            headerObject = JSON.parseObject(baseRequestJson, JSONObject.class);
            params.putAll(headerObject);
        }
        // 生成签名
        String signature = SignUtils.getSignStr(params, null);
        headerObject.put("sign", signature);
        // 将签名添加到请求头中
        template.header("Authorization", "Bearer " + headerObject.toJSONString());
    }
}
